<template>
  <basic-container>
    <el-tabs type="border-card" style="margin: 10px">
      <el-tab-pane label="">
        <avue-form ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption">
          <!-- <template slot="productSequenceNumber">
            <el-input
              ref="sequenceNumberProperties"
              @keyup.enter.native="enterProductSequenceNumber(badCodeModel.productSequenceNumber)"
              placeholder="请输入产品序列号"
              v-model="badCodeModel.productSequenceNumber"
              clearable
            >
            </el-input>
          </template>
          <template slot="workOrderNo">
            <el-input ref="workOrderNo" @keyup.enter.native="enterWorkOrderNo(badCodeModel.workOrderNo)" placeholder="请输入工单号" v-model="badCodeModel.workOrderNo" clearable>
            </el-input>
          </template> -->
          <template slot="btn">
            <div class="btn-style">
              <el-button type="primary" size="small" icon="el-icon-search" @click="submitBadCode('search')">搜 索</el-button>
              <el-button size="small" icon="el-icon-delete" @click="reset">清 空</el-button>
            </div>
          </template>
        </avue-form>
      </el-tab-pane>
    </el-tabs>
    <el-tabs type="border-card" style="margin: 10px">
      <el-tab-pane label="">
        <div class="mark-btn">
          <div class="btn-wrapper-left">
            <el-button type="primary" size="small" v-if="permission.failureconfirm_repair" @click="handleRepair">在线维修</el-button>
            <el-button type="primary" size="small" v-if="permission.failureconfirm_repair" @click="offlineRepair">离线维修</el-button>
            <el-button type="success" size="small" v-if="permission.failureconfirm_relieve" @click="handleFailure">解除不良</el-button>
            <el-button type="danger" size="small" v-if="permission.failureconfirm_scrap" @click="handleScrap">报废</el-button>
          </div>
          <div class="btn-wrapper-right">
            <el-button type="primary" size="small" v-if="permission.failureconfirm_repair" @click="handleRouteAutoConfig">工序自动判定配置</el-button>
          </div>
        </div>
        <el-table
          v-loading="loading"
          ref="multipleTable"
          height="calc(100vh - 515px)"
          :data="data"
          border
          @row-dblclick="rowDblclick"
          style="width: 100%"
          header-row-class-name="header-color"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          @select="select"
          class="el-table--small"
        >
          <el-table-column type="selection" width="50" align="center"> </el-table-column>
          <el-table-column v-for="item in column" :label="item.label" :width="item.width" style="color: #25252" :prop="item.prop" :key="item.prop">
            <template slot-scope="scope">
              <span v-if="item.prop === 'status'">
                <el-tag v-if="scope.row.status == 1">待处理</el-tag>
                <el-tag v-else-if="scope.row.status == 2" type="success">维修</el-tag>
                <el-tag v-else-if="scope.row.status == 3" type="danger">报废</el-tag>
              </span>
              <span v-else-if="item.prop === 'objectType'">
                <span v-if="scope.row.objectType == 'PRODUCT'">产品序列号</span>
                <span v-if="scope.row.objectType == 'WORKORDER'">工单登记不良</span>
                <span v-if="scope.row.objectType == 'PACKING'">包装条码</span>
                <span v-if="scope.row.objectType == 'CARRIER'">载具</span>
              </span>
              <span v-else>
                {{ scope.row[item.prop] }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="page.sizes"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="60%" top="5vh" @close="closeDialog">
      <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="submitEvent" @reset-change="resetChange">
        <!-- <template slot="failureCode">
          <div v-for="(item, index) of failureList" :key="index" class="detail-form" style="display: flex">
            <el-input
              placeholder="请扫描不良代码"
              v-model="failureList[index].failureCode"
              style="margin-bottom: 10px"
              @keyup.enter.native="checkFailureName(item, index)"
              clearable
            ></el-input>
            <i class="iconfont iconicon_roundclose" v-if="index + 1 !== failureList.length" @click="handleIconDelete()" style="margin-left: 10px"></i>
            <i class="iconfont iconicon_roundadd" v-else @click="handleIconAdd()" style="margin-left: 10px"></i>
          </div>
        </template> -->
      </avue-form>
    </el-dialog>
    <el-dialog append-to-body :close-on-click-modal="false" title="工序自动判定配置" :visible.sync="routeConfigDialog" v-if="routeConfigDialog" width="40%" top="5vh">
      <div class="sail-header-dialog-content">
        <avue-form ref="routeConfigPropertiesRef" v-model="routeConfigProperties" :option="routeConfigOption">
          <!-- <template slot="failureCode">
          <el-input
            v-model="routeConfigProperties.failureCode"
            name="failureCode"
            :clearable="true"
            placeholder="输入不良代码或者扫描代码"
            suffix-icon="iconfont iconicon_scan"
            style="width: 100%"
            @keydown.enter.native="enterFailureCode(routeConfigProperties.failureCode)"
          >
            <el-button slot="append" icon="el-icon-search" @click="openFailureCommonModal()"></el-button>
          </el-input>
        </template>
        <template slot="failureName">
          <avue-select
            multiple
            clearable="false"
            class="failureNameSelect"
            popper-class="el-select_popperClass"
            v-model="failureNameForm"
            @change="handleFailureNameDelete($event)"
            placeholder="不良现象"
            :dic="failureNameDic"
            readonly="true"
          >
          </avue-select>
        </template> -->
        </avue-form>
        <avue-crud ref="crud" :option="routeTableOption" :table-loading="routeTableLoading" :data="routeTabledata" @row-del="rowDel">
          <template slot="menuLeft">
            <el-button type="primary" size="small" @click="handleInput">录 入</el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-product/mro/centerproduct/list" :option="option" :page="page" :query="query" file-name="不良确认"> </export-comp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import {
  getPageList,
  getRouteList,
  submitRoute,
  scrap,
  flagFailure,
  flagRepiar,
  getLineList,
  getRoutes,
  onlineRepiar,
  checkFailure,
  routeList,
  removeRoute
} from '@/api/repair/failureconfirm';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp/index';
import repairDetail from '@/components/repair/detail.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  name: 'RepairFailureConfirm',
  components: {
    exportComp,
    repairDetail,
    CommonModalTemplate
  },
  data() {
    return {
      loading: false,
      viewDialog: false,
      rowData: {},
      dataTempList: [], //临时缓存数据
      badCodeModel: {
        objectType: '',
        productSequenceNumber: '',
        workOrderNo: '',
        failureName: ''
      },
      tableOption: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        sizes: [15, 20, 30, 40, 50, 100]
      },
      lineNameList: [],
      failureList: [
        {
          id: 1,
          failureCode: ''
        }
      ],
      repairRouteList: [],
      failureNameForm: [],
      failureNameDic: [],
      routeTableLoading: false,
      routeTabledata: [],
      routeTableOption: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        emptyBtn: false,
        searchBtn: false,
        searchSpan: 24,
        border: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: true,
        selection: false,
        menuWidth: 100, //弹框内字段宽度属性
        columnBtn: false,
        refreshBtn: false,
        indexLabel: '序号',
        column: [
          {
            label: '工序',
            prop: 'workstationName'
          },
          {
            label: '维修类型',
            prop: 'confirmResult',
            type: 'select',
            dicData: [
              {
                label: '在线维修',
                value: 'ONLINE'
              },
              {
                label: '离线维修',
                value: 'OFFLINE'
              }
            ]
          }
        ]
      },
      routeConfigDialog: false,
      routeConfigProperties: {},
      routeConfigOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '工序',
            prop: 'routeName',
            type: 'tree',
            dicUrl: '/api/mes-product/apaasworkstation/workstation/list',
            multiple: true,
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择工序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '维修类型',
            prop: 'confirmResult',
            type: 'select',
            value: 'OFFLINE',
            dicData: [
              {
                label: '在线维修',
                value: 'ONLINE'
              },
              {
                label: '离线维修',
                value: 'OFFLINE'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择维修类型',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      badCodeOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            span: 6
          },
          {
            label: '产品序列号',
            prop: 'productSn',
            span: 6
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            span: 6
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            span: 6
          },
          {
            label: '登记产线',
            prop: 'lineName',
            span: 6
          },
          {
            label: '登记工序',
            prop: 'routeName',
            span: 6
          },
          {
            label: '登记工位',
            prop: 'stationName',
            span: 6
          },
          {
            label: '登记时间',
            prop: 'registerTime',
            type: 'datetimerange',
            span: 8,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '',
            prop: 'btn',
            span: 24,
            labelWidth: 0
          }
        ]
      },
      column: [
        {
          label: '工单号',
          prop: 'workOrderNo'
        },
        {
          label: '产品序列号',
          prop: 'productSn',
          search: true
        },
        {
          label: '产品编码',
          prop: 'productPartNo'
        },
        {
          label: '产品名称',
          prop: 'productPartName'
        },
        {
          label: '产品型号',
          prop: 'productPartModel'
        },
        {
          label: '不良数',
          prop: 'badQuantity'
        },
        {
          label: '登记产线',
          prop: 'lineName'
        },
        {
          label: '登记工序',
          prop: 'routeName'
        },
        {
          label: '登记工位',
          prop: 'stationName'
        },
        {
          label: '不良现象',
          prop: 'badPhenomenonName'
        },
        {
          label: '登记说明',
          prop: 'registerDescription'
        },
        {
          label: '登记人员',
          prop: 'registerUserName'
        },
        {
          label: '不良登记时间',
          prop: 'registerTime'
        },
        {
          label: '已维修次数',
          prop: 'repairTimes'
        }
      ],
      badCodes: [], //所有不良代码信息
      form: {},
      properties: {
        imageList: []
      },
      query: {},
      loading: false,
      showDialog: false,
      title: '',
      timer: null,
      modalName: '',
      tempData: [],
      selectionList: [],
      serchIds: [],
      productSequenceNumber: '',
      propertiesOption: {
        labelWidth: '150',
        menuPosition: 'right', //表单菜单按钮的排列方式
        group: []
      },
      data: [],
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        searchLabelWidth: 100,
        dialogClickModal: false,
        border: true,
        columnBtn: false,
        viewBtn: false,
        addBtn: false,
        selection: false,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        index: true,
        indexLabel: '序号',
        refreshBtn: false,
        menuWidth: 100,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '不良数',
            prop: 'quantity'
          },
          {
            label: '登记产线',
            prop: 'lineName'
          },
          {
            label: '登记工序',
            prop: 'fromRouteName'
          },
          {
            label: '登记工位',
            prop: 'fromStationName'
          },
          {
            label: '不良现象',
            prop: 'failureName'
          },
          {
            label: '不良现象说明',
            prop: 'instructions',
            hide: true
          }
        ]
      },
      rowIndex: 0
    };
  },
  created() {},
  mounted() {
    this.onLoad(this.page);
  },
  beforeDestroy() {},
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },

  methods: {
    resetChange() {
      if (this.selectionList.length === 1) {
        this.properties = this.selectionList[0];
      }
    },
    resetData() {
      this.routeConfigProperties = {};
      this.failureNameForm = [];
      this.failureNameDic = [];
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeRoute(row.id);
        })
        .then(() => {
          this.routeTableLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    // handleFailureNameDelete(items) {
    //   this.failureNameDic = this.failureNameDic.filter((item) => {
    //     if (items.includes(item.code)) {
    //       return item;
    //     }
    //   });
    // },
    routeTableLoad(params = {}) {
      this.routeTableLoading = true;
      getRouteList(params).then((res) => {
        const data = res.data.data;
        this.routeTabledata = data || [];
        this.routeTableLoading = false;
      });
    },
    handleInput() {
      this.$refs.routeConfigPropertiesRef.validate((valid, done) => {
        if (valid) {
          let configs = this.repairRouteList
            .filter((item) => {
              return this.routeConfigProperties.routeName.includes(item.id);
            })
            .map((item) => {
              return {
                workstationId: item.id,
                workstationCode: item.code,
                workstationName: item.name,
                confirmResult: this.routeConfigProperties.confirmResult
              };
            });
          let params = {
            configs
          };
          submitRoute(params).then((res) => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.resetData();
            this.routeTableLoad();
          });
        }
        done();
      });
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'failureModal':
          let productHandlingResultFailureList = [];
          let productHandlingResultFailureTypeList = [];
          let failureName = [];
          rowData.forEach((element) => {
            productHandlingResultFailureList.push({
              resultId: element.id,
              resultCode: element.code,
              resultName: element.name
            });
            productHandlingResultFailureTypeList.push({
              resultId: element.failureTypeId,
              resultCode: element.failureTypeCode,
              resultName: element.failureTypeName
            });
            failureName.push(element.name);
          });
          this.detailData[this.rowIndex].productHandlingResultFailureList = productHandlingResultFailureList;
          this.detailData[this.rowIndex].productHandlingResultFailureTypeList = productHandlingResultFailureTypeList;
          this.detailData[this.rowIndex].failureName = failureName.join(',');

          break;
        case 'failureCode':
          let tempList = this.failureNameDic.concat(
            this._map(rowData, (item) => {
              return {
                label: item.name,
                value: item.code,
                ...item
              };
            })
          );
          this.failureNameDic = this._uniqWith(tempList, (arrVal, othVal) => {
            return arrVal.value === othVal.value;
          });
          this.failureNameForm = this.failureNameDic.map((item) => item.code);
          let failureTypeNames = this.failureNameDic
            .map((item) => item.failureTypeName)
            .filter((value) => {
              return value !== undefined;
            });

          this.$set(this.routeConfigProperties, 'failureTypeName', String(this._uniq(failureTypeNames)));
          break;
        default:
          break;
      }
    },
    handleRouteAutoConfig() {
      this.routeConfigDialog = true;
      this.resetData();
      routeList().then((res) => {
        let data = res.data.data;
        this.repairRouteList = data;
      });
      this.routeTableLoad();
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    enterProductSequenceNumber(productSequenceNumber) {
      if (!productSequenceNumber) {
        this.$message({
          type: 'warning',
          message: '产品序列号不能为空！'
        });
        return;
      }
      this.submitBadCode('enter', 'productSequenceNumber');
    },
    enterWorkOrderNo(workOrderNo) {
      if (!workOrderNo) {
        this.$message({
          type: 'warning',
          message: '工单号不能为空！'
        });
        return;
      }
      this.submitBadCode('enter', 'workOrderNo');
    },
    enterFailureName(failureName) {
      if (!failureName) {
        this.$message({
          type: 'warning',
          message: '不良现象不能为空！'
        });
        return;
      }
      this.submitBadCode('enter', 'failureName');
    },
    handleIconDelete(idx) {
      let failureList = this._cloneDeep(this.failureList);
      failureList.splice(idx, 1);
      this.failureList = this._cloneDeep(failureList);
    },
    handleIconAdd() {
      this.failureList.push({
        id: this.failureList.length + 1,
        failureCode: ''
      });
    },
    rowClick(row) {},
    //根据序列号录入不良代码
    async submitBadCode(title, input = '') {
      this.$refs.badConfirmProperties.validate((valid, done) => {
        if (valid) {
          let params = {};
          this.page.pageSize = 15;
          this.page.currentPage = 1;
          this.page.total = 0;
          this._forEach(this.badCodeModel, (value, key) => {
            if (value) {
              params[key] = value;
            }
          });
          if (params.registerTime) {
            params.startTime = params.registerTime[0];
            params.endTime = params.registerTime[1];
            delete params.registerTime;
          }
          this.loading = true;
          getPageList(this.page.currentPage, this.page.pageSize, Object.assign(params)).then((res) => {
            let resObj = res.data.data;
            let data = resObj.records || [];
            this.data = data;
            this.page.total = resObj.total;
            this.loading = false;
            // if (title == 'enter') {
            //   // this.dataTempList = this.dataTempList.concat(data);
            //   // let obj = {};
            //   // let newArr = [];
            //   // this.dataTempList.forEach((item) => {
            //   //   if (!obj[item.id]) {
            //   //     obj[item.id] = '1';
            //   //     newArr.push(item);
            //   //   }
            //   // });
            //   // console.log(this.dataTempList, data, 88888);
            //   // this.data = newArr;
            //   // this.dataTempList = newArr;
            //   this.page.total = this.data.length;
            // } else {
            //   this.data = data;
            //   this.page.total = resObj.total;
            // }
          });
          done();
        }
      });
    },

    /**
     * 不良确认 选中逻辑
     *
     */
    badCodeEntry(productSequenceNumber = '', type, workOrderNo = '', failureName = '', objectType = '', responseData = []) {
      let data = this._cloneDeep(this.data);
      let items = this._remove(data, (item) => {
        if (!item.productSequenceNumber) {
          item.productSequenceNumber = '';
        }
        if (!item.workOrderNo) {
          item.workOrderNo = '';
        }
        if (!item.objectType) {
          item.objectType = '';
        }
        if (!item.failureName) {
          item.failureName = '';
        }
        return item.productSequenceNumber === productSequenceNumber && item.workOrderNo == workOrderNo && item.objectType == objectType && item.failureName == failureName;
      }).map((item) => {
        return item;
      });
      items = responseData.length > 0 ? responseData : items;
      if (type === 'input') {
        for (let i = 0; i < items.length; i++) {
          let lock = true;
          let n = 0;
          for (let j = 0; j < this.data.length; j++) {
            if (!this.data[j].isCheck && lock) {
              //只会执行一次
              n = j; //记录从上往下未选中的下标
              lock = false;
            }
            if (items[i].id === this.data[j].id) {
              //数据位置互换
              console.log(n, j, 'nj');
              let temp = this.data[j];
              this.data[j] = this.data[n];
              this.data[n] = temp;
              temp.isCheck = true;
              this.$refs.multipleTable.toggleRowSelection(temp);
            }
          }
        }
      } else {
        for (let i = 0; i < 1; i++) {
          for (let j = 0; j < this.data.length; j++) {
            if (items[i].id === this.data[j].id) {
              this.data[j].isCheck = false;
              this.$refs.multipleTable.toggleRowSelection(this.data[j]);
            }
          }
        }
      }
      this.filtersFailureSequenceNumber();
    },

    filtersFailureSequenceNumber() {
      this.selectionList = this._filter(this.data, (item) => {
        return item.isCheck === true;
      });
    },
    handleSelectionChange(list) {
      this.selectionList = list;
    },

    //录入序列号双击取消选中
    rowDblclick(row) {
      // if (row.isCheck) {
      //   this.badCodeEntry(row.productSequenceNumber, 'cancel', row.workOrderNo, row.failureName, row.objectType, []);
      // }
    },

    focusSequenceNumber() {
      this.$nextTick(() => {
        this.$refs.sequenceNumberProperties.focus();
      });
    },

    closeDialog() {
      this.$refs.properties && this.$refs.properties.resetForm();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getPageList(page.currentPage, page.pageSize, params).then((res) => {
        let data = res.data.data;
        this.data = data.records || [];
        this.page.total = data.total;
        this.dataTempList = [];
        this.loading = false;
      });
    },
    reset() {
      this.$refs.badConfirmProperties.resetForm();
      this.dataTempList = [];
      this.data = [];
      this.onLoad(this.page);
    },
    getLineSelectList() {
      getLineList().then((res) => {
        this.lineNameList = res.data.data;
      });
    },
    checkFailureName(item, idx) {
      checkFailure({
        checkType: 'FAILURE',
        code: item.failureCode
      }).then(
        (res) => {
          let data = res.data.data;
          for (let i = 0; i < this.failureList.length; i++) {
            if (this.failureList[i].id === data.id) {
              this.failureList[idx].failureCode = '';
              this.$message({
                type: 'warning',
                message: '不良代码已存在，请勿重复扫描！!'
              });
              return;
            }
          }
          this.failureList.forEach((item, i) => {
            if (idx === i) {
              item.id = data.id;
              item.failureCode = data.code;
            }
          });
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (err) => {
          this.failureList.forEach((item, i) => {
            if (idx === i) {
              item.failureCode = '';
            }
          });
        }
      );
    },
    submitEvent() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          if (this.title === '在线维修') {
            let repairRegisterIdList = this.selectionList.map((item) => item.id);
            let params = {
              confirmDescription: this.properties.remark,
              returnRouteId: this.properties.repairRoute,
              repairRegisterIdList
            };
            onlineRepiar(params).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              this.onLoad(this.page);
            });
            done();
          } else if (this.title === '离线维修') {
            let repairRegisterIdList = this.selectionList.map((item) => item.id);
            let params = {
              confirmDescription: this.properties.remark,
              repairRegisterIdList
            };
            flagRepiar(params).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              this.onLoad(this.page);
            });
            done();
          } else if (this.title === '解除不良') {
            let repairRegisterIdList = this.selectionList.map((item) => item.id);
            let params = {
              confirmDescription: this.properties.remark,
              repairRegisterIdList
            };
            flagFailure(params).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              this.onLoad(this.page);
            });
            done();
          } else if (this.title === '报废') {
            let repairRegisterIdList = this.selectionList.map((item) => item.id);
            let params = {
              confirmDescription: this.properties.remark,
              repairRegisterIdList
            };
            scrap(params).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              this.onLoad(this.page);
            });
            done();
          }
        }
      });
    },
    // deleteTempData(ids) {
    //   ids.forEach((id) => {
    //     let i = this.dataTempList.findIndex((item) => item.id == id);
    //     this.dataTempList.splice(i, 1);
    //   });
    //   this.data = this._cloneDeep(this.dataTempList);
    //   if (this.data.length === 0) {
    //     this.onLoad(this.page);
    //   }
    // },
    tableRowClassName({ row, rowIndex }) {
      let className = row.isCheck ? 'scan-entry-row' : '';
      return className;
    },

    /**
     * 标记报废
     */
    handleScrap() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.title = '报废';
      this.propertiesOption.submitText = '提交';
      this.propertiesOption.labelWidth = '100';
      this.propertiesOption.group = [];
      this.propertiesOption.group = [
        {
          label: '不良信息',
          arrow: false,
          prop: 'failureTitle',
          icon: 'el-icon-vertical-bar',
          display: false,
          labelWidth: 150,
          column: [
            {
              label: '工单号',
              prop: 'workOrderNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品序列号',
              prop: 'productSn',
              span: 10,
              disabled: true
            },
            {
              label: '产品编码',
              prop: 'productPartNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品名称',
              prop: 'productPartName',
              span: 10,
              disabled: true
            },
            {
              label: '产品型号',
              prop: 'productPartModel',
              span: 10,
              disabled: true
            },
            {
              label: '不良数',
              prop: 'badQuantity',
              span: 10,
              disabled: true
            },
            {
              label: '登记产线',
              prop: 'lineName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工序',
              prop: 'routeName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工位',
              prop: 'stationName',
              span: 10,
              disabled: true
            },
            {
              label: '不良现象',
              prop: 'badPhenomenonName',
              span: 10,
              disabled: true
            }
          ]
        },
        {
          label: '报废原因',
          arrow: false,
          prop: 'repairRouteTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '报废原因',
              prop: 'remark',
              type: 'textarea',
              maxRows: 3,
              minRows: 3,
              span: 24,
              showWordLimit: true,
              rules: [
                {
                  required: true,
                  message: '请输入报废原因',
                  trigger: 'blur'
                }
              ]
            }
          ]
        }
      ];
      let failureTitle = this.findNode(this.propertiesOption.group, 'failureTitle');
      if (this.selectionList.length == 1) {
        failureTitle.display = true;
        this.properties = this.selectionList[0];
      } else {
        failureTitle.display = false;
      }
      this.properties.remark = '';
      this.showDialog = true;
    },
    /**
     * 解除不良
     */
    handleFailure() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      if (this.selectionList.length == 1) {
        this.properties = this.selectionList[0];
      }
      this.title = '解除不良';
      this.propertiesOption.submitText = '提交';
      this.propertiesOption.labelWidth = '100';
      this.propertiesOption.group = [];
      this.propertiesOption.group = [
        {
          label: '不良信息',
          arrow: false,
          prop: 'failureTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '工单号',
              prop: 'workOrderNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品序列号',
              prop: 'productSn',
              span: 10,
              disabled: true
            },
            {
              label: '产品编码',
              prop: 'productPartNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品名称',
              prop: 'productPartName',
              span: 10,
              disabled: true
            },
            {
              label: '产品型号',
              prop: 'productPartModel',
              span: 10,
              disabled: true
            },
            {
              label: '不良数',
              prop: 'badQuantity',
              span: 10,
              disabled: true
            },
            {
              label: '登记产线',
              prop: 'lineName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工序',
              prop: 'routeName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工位',
              prop: 'stationName',
              span: 10,
              disabled: true
            },
            {
              label: '不良现象',
              prop: 'badPhenomenonName',
              span: 10,
              disabled: true
            }
          ]
        },
        {
          label: '解除原因',
          arrow: false,
          prop: 'repairRouteTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '解除原因',
              prop: 'remark',
              type: 'textarea',
              maxRows: 3,
              minRows: 3,
              span: 24,
              maxlength: 50,
              showWordLimit: true,
              rules: [
                {
                  required: true,
                  message: '请输入解除原因',
                  trigger: 'blur'
                }
              ]
            }
          ]
        }
      ];
      let failureTitle = this.findNode(this.propertiesOption.group, 'failureTitle');
      if (this.selectionList.length == 1) {
        failureTitle.display = true;
        this.properties = this.selectionList[0];
      } else {
        failureTitle.display = false;
      }
      this.properties.remark = '';
      this.showDialog = true;
    },
    /**
     * 离线维修
     */
    offlineRepair() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      if (this.selectionList.length == 1) {
        this.properties = this.selectionList[0];
      }
      this.propertiesOption.submitText = '提交';
      this.title = '离线维修';
      this.propertiesOption.column = [];
      this.propertiesOption.group = [
        {
          label: '不良信息',
          arrow: false,
          prop: 'failureTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '工单号',
              prop: 'workOrderNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品序列号',
              prop: 'productSn',
              span: 10,
              disabled: true
            },
            {
              label: '产品编码',
              prop: 'productPartNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品名称',
              prop: 'productPartName',
              span: 10,
              disabled: true
            },
            {
              label: '产品型号',
              prop: 'productPartModel',
              span: 10,
              disabled: true
            },
            {
              label: '不良数',
              prop: 'badQuantity',
              span: 10,
              disabled: true
            },
            {
              label: '登记产线',
              prop: 'lineName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工序',
              prop: 'routeName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工位',
              prop: 'stationName',
              span: 10,
              disabled: true
            },
            {
              label: '不良现象',
              prop: 'badPhenomenonName',
              span: 10,
              disabled: true
            }
          ]
        },
        {
          label: '处理意见',
          arrow: false,
          prop: 'failureReason',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '处理意见',
              prop: 'remark',
              type: 'textarea',
              maxRows: 3,
              minRows: 3,
              span: 24,
              maxlength: 50,
              showWordLimit: true,
              rules: [
                {
                  required: true,
                  message: '请输入处理意见',
                  trigger: 'blur'
                }
              ]
            }
          ]
        }
      ];
      let failureTitle = this.findNode(this.propertiesOption.group, 'failureTitle');
      if (this.selectionList.length == 1) {
        failureTitle.display = true;
        this.properties = this.selectionList[0];
      } else {
        failureTitle.display = false;
      }
      this.properties.remark = '';
      this.showDialog = true;
    },

    /**
     * 在线维修
     */
    handleRepair() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let workorderUniqs = this._uniqWith(this.selectionList, (arrVal, othVal) => {
        return arrVal.workOrderId === othVal.workOrderId;
      });
      if (workorderUniqs.length > 1) {
        this.$message.warning('不同工单不可进行在线维修');
        return;
      }
      if (this.selectionList.length == 1) {
        this.properties = this.selectionList[0];
      }
      this.title = '在线维修';
      this.propertiesOption.submitText = '提交';
      this.propertiesOption.column = [];
      this.propertiesOption.group = [
        {
          label: '不良信息',
          arrow: false,
          prop: 'failureTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '工单号',
              prop: 'workOrderNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品序列号',
              prop: 'productSn',
              span: 10,
              disabled: true
            },
            {
              label: '产品编码',
              prop: 'productPartNo',
              span: 10,
              disabled: true
            },
            {
              label: '产品名称',
              prop: 'productPartName',
              span: 10,
              disabled: true
            },
            {
              label: '产品型号',
              prop: 'productPartModel',
              span: 10,
              disabled: true
            },
            {
              label: '不良数',
              prop: 'badQuantity',
              span: 10,
              disabled: true
            },
            {
              label: '登记产线',
              prop: 'lineName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工序',
              prop: 'routeName',
              span: 10,
              disabled: true
            },
            {
              label: '登记工位',
              prop: 'stationName',
              span: 10,
              disabled: true
            },
            {
              label: '不良现象',
              prop: 'badPhenomenonName',
              span: 10,
              disabled: true
            }
          ]
        },
        {
          label: '指定返回工站',
          arrow: false,
          prop: 'repairRouteTitle',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '指定返回工站',
              prop: 'repairRoute',
              type: 'select',
              dicData: [],
              props: {
                label: 'routeName',
                value: 'id'
              },
              rules: [
                {
                  required: true,
                  message: '请选择指定返回工站',
                  trigger: 'blur'
                }
              ]
            }
          ]
        },
        {
          label: '处理意见',
          arrow: false,
          prop: 'remark',
          icon: 'el-icon-vertical-bar',
          labelWidth: 150,
          column: [
            {
              label: '处理意见',
              prop: 'remark',
              type: 'textarea',
              maxRows: 3,
              minRows: 3,
              span: 24,
              maxlength: 50,
              showWordLimit: true,
              rules: [
                {
                  required: true,
                  message: '请输入处理意见',
                  trigger: 'blur'
                }
              ]
            }
          ]
        }
      ];
      let failureTitle = this.findNode(this.propertiesOption.group, 'failureTitle');
      if (this.selectionList.length == 1) {
        failureTitle.display = true;
        this.properties = this.selectionList[0];
      } else {
        failureTitle.display = false;
      }
      this._forEach(workorderUniqs, (item) => {
        this.getFailureRoute(item.workOrderId);
      });
      this.properties.remark = '';
      this.showDialog = true;
    },
    getFailureRoute(workorderId) {
      getRoutes({
        workorderId
      }).then((res) => {
        let repairRouteTitle = this.findNode(this.propertiesOption.group, 'repairRouteTitle');
        let repairRouteColumn = this.findObject(repairRouteTitle.column, 'repairRoute');
        repairRouteColumn.dicData = res.data.data;
      });
    },
    findNode(list = [], prop) {
      let node;
      list.forEach((ele) => {
        if (ele.prop === prop) node = ele;
      });
      return node;
    },
    handleDetail(data) {
      this.isAuto = data.registrySource == 'AUTO';
      this.activeName = 'first';
      this.viewDialog = true;
      this.rowData = structuredClone(data);
    },
    /*
     * 不良代码选择框
     */
    openFailureCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'failureCode';
      this.tableOption = {
        modalTitle: '选择不良代码信息（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_PHENOMENON',
        isPage: true,
        index: false,
        searchBtn: true,
        rowSelectionType: 'mutiple',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '不良代码',
            prop: 'code',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良现象描述',
            prop: 'name',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良现象描述',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    }
  },
  watch: {}
};
</script>

<style scoped lang="scss">
::v-deep .el-table .header-color {
  color: rgba(0, 0, 0, 0.85) !important;
  th {
    word-break: break-word;
    color: rgba(0, 0, 0, 0.85);
    background-color: #fafafa;
  }
}

::v-deep .el-table .scan-entry-row {
  background: #caf982;
}

::v-deep .mark-btn {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 10px;
}
.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
::v-deep .el-card__body {
  padding: 0;
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}

.tdStyle {
  background: #fafafa;
  font-weight: 700;
  color: #909399;
  text-align: right;
  width: auto;
  padding-right: 20px;
  white-space: nowrap;
}

td {
  padding: 5px;
  border: 1px solid #ebeef5;
}
.btn-style {
  display: inline-block;
  float: right;
}
.page {
  width: 100%;
  padding: 20px 0px;
  display: flex;
  justify-content: end;
}

::v-deep .failureNameSelect .el-input__suffix {
  display: none;
}
.el-table--small {
  font-size: 12px;
}
.detailTitle {
  font-size: 16px;
  font-weight: bold;
  height: 20px;
  padding: 10px 0;
  color: rgba(0, 0, 0, 0.85);
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  .dot {
    background-color: #66b1ff;
    width: 10px;
    height: 20px;
    margin-right: 8px;
  }
  .title {
    height: 20px;
    margin-bottom: 0;
  }
}
::v-deep .el-tabs__header {
  display: none;
}

::v-deep .el-tabs .avue-form__menu {
  display: none;
}
</style>
